/* Controller.m:
 * You may freely copy, distribute, and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or  implied, as to its
 * fitness for any particular use.
 *
 * Controller is providing the high level interface to the main menu commands
 * like open, close, evaluate, and clear.
 *
 */
 
#import<foundation/NSString.h>
#import <foundation/NSException.h>

#import "Controller.h"
#import "Evaluator.h"

void MyTopLevelErrorHandler(NXHandler *errorState);

@implementation Controller

#define DEFAULT_LIBRARY "Library/Models"

- appDidInit:sender
{
 	NXSetTopLevelErrorHandler(MyTopLevelErrorHandler);

	[self open:sender];
	return self;
}

void MyTopLevelErrorHandler(NXHandler *errorState)
{
 	if (errorState->code >= NSExceptionBase &&
	   errorState->code <= NSLastException) {
	   NSException *exception = (id) errorState->data1;

	 NSLog(@"%@: %@\n", [exception exceptionName], [exception exceptionReason]);
	    }
}


- open:sender
{
    char **files;
    char *path;
    const char *directory;
    const char *const types[] = { "eomodel", 0 };
    id openPanel;

    openPanel = [OpenPanel new];
    [openPanel allowMultipleFiles:YES];
   
	path = malloc((MAXPATHLEN +1)*sizeof(char));
    sprintf(path, "%s/%s", getenv("HOME"), DEFAULT_LIBRARY);
    if ([openPanel runModalForDirectory:path file:NULL types:types])
	if ((files = (char **) [openPanel filenames]) != NULL)
	{
	    directory = [openPanel directory];
	    for (; *files; ++files)
	    {
		sprintf(path, "%s/%s", directory, *files);
		[self openFileNamed:path];
	    }
	}
	free(path);
    return self;
}

- openFileNamed:(const char *)filename
{
    return [[Evaluator alloc] initWithModelFile:
    				[[NSString alloc]initWithCString:filename]];
}

- evaluate:sender
{
    [[[NXApp mainWindow] delegate] evaluate:sender];
    return self;
}

- clear:sender
{
    [[[NXApp mainWindow] delegate] clear:sender];
    return self;
}


- close:sender
{
    [[[NXApp mainWindow] delegate] close:sender];
    return self;
}

@end